//
//  NYSearchResultViewController.m
//  Nooryes
//
//  Created by baken on 2020/3/10.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYSearchResultViewController.h"
#import "NYRecommendCollectionViewCell.h"
#import "NYArticleListModel.h"
#import "NYTopicListModel.h"
#import "NYTopicListTableViewCell.h"
#import "NYTopicArticlesViewController.h"
#import "NYSearchViewModel.h"
#import "NYSearchUserModel.h"
#import "NYOtherUserViewController.h"
#import "NYSearchUserTableViewCell.h"
#import "AccountModel.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "NYAlertView.h"
#import "NYTitleViewSearchBar.h"
#import "NYArticleDetailViewController.h"

@interface NYSearchResultViewController ()<CHTCollectionViewDelegateWaterfallLayout>

@property (nonatomic,strong) NYTitleViewSearchBar *searchBar;

@property (nonatomic,strong) NYSearchViewModel *searchVM;

@property (nonatomic,strong) UIButton *selectedBtn;//当前被选中的按钮

@property (nonatomic,strong) UIButton *selectedArtBtn;

@property (nonatomic,strong) UIButton *selectedTopicBtn;

@property (weak, nonatomic) IBOutlet UIView *redLine;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UITableView *topicTableView;
@property (weak, nonatomic) IBOutlet UITableView *userTableView;

@property (weak, nonatomic) IBOutlet UIView *topicView;
@property (weak, nonatomic) IBOutlet UIView *collectionBackView;
@property (weak, nonatomic) IBOutlet UIButton *didSelectedTopBtn;
@property (weak, nonatomic) IBOutlet UIButton *didselectedArtBtn;
@property (weak, nonatomic) IBOutlet UIButton *didSelectedTopicBtn;

@end

@implementation NYSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topicTableView.rowHeight = (kScreenWidth-24-6)*0.33 + 35;
    self.userTableView.rowHeight = 88;
    self.topicTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.userTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.collectionViewLayout = layout;
    [self.collectionView registerClass:[NYRecommendCollectionViewCell class] forCellWithReuseIdentifier:kNYRecommendCollectionViewCell];
    [self onArticle:nil];
    
    self.searchVM.keys = self.keys;
    NYTitleViewSearchBar *searchBar = [[NYTitleViewSearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-100, 30)];
    self.navigationItem.titleView = searchBar;
    searchBar.searchBar.text = self.keys;
    
    searchBar.searchBlock = ^(NSString * text) {
        [self onSearch:text];
    };
    
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.searchVM.articlePage = 1;
        [self.searchVM getSearchAriticlesWithCompletionHandle:^(NSError *error) {
            if (!error) {
                //                if (self.searchVM.articlesArray.count == 0) {
                //                    alert.title = @"暂无数据";
                //                    [alert showAlert:^{
                //                    }];
                //                }
                
                [self.collectionView reloadData];
            } else {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                [alert showAlert:^{
                }];
            }
            [self.collectionView.mj_header endRefreshing];
        }];
    }];
    
    
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.searchVM.articlePage++;
        [self.searchVM getSearchAriticlesWithCompletionHandle:^(NSError *error) {
            if (!error) {
                
                [self.collectionView reloadData];
            }
            [self.collectionView.mj_footer endRefreshing];
        }];
    }];
    
    
    self.userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.searchVM.userPage = 1;
        [self.searchVM getSearchUserListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                //                if (self.searchVM.userArray.count == 0) {
                //                    alert.title = @"暂无数据";
                //                    [alert showAlert:^{
                //                    }];
                //                }
                [self.userTableView reloadData];
            } else {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                [alert showAlert:^{
                }];
            }
            [self.userTableView.mj_header endRefreshing];
        }];
    }];
    
    self.userTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.searchVM.userPage++;
        [self.searchVM getSearchUserListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.userTableView reloadData];
            }
            [self.userTableView.mj_footer endRefreshing];
        }];
    }];
    
    
    
    self.topicTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.searchVM.topicPage =1;
        [self.searchVM getSearchTopicListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                //                if (self.searchVM.topicArray.count == 0) {
                //                    alert.title = @"暂无数据";
                //                    [alert showAlert:^{
                //                    }];
                //                }
                [self.topicTableView reloadData];
                
            } else {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
                [alert showAlert:^{
                }];
            }
            [self.topicTableView.mj_header endRefreshing];
        }];
    }];
    
    self.topicTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.searchVM.topicPage++;
        [self.searchVM getSearchTopicListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.topicTableView reloadData];
            }
            [self.topicTableView.mj_footer endRefreshing];
        }];
    }];
    
    
    
    [self.collectionView.mj_header beginRefreshing];
    self.selectedBtn = self.didSelectedTopBtn;
    self.selectedArtBtn = self.didselectedArtBtn;
    self.selectedTopicBtn = self.didSelectedTopicBtn;
}



- (IBAction)onArticle:(id)sender {
    UIButton *button = (UIButton *)sender;
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
    self.redLine.center = CGPointMake(button.center.x, self.redLine.center.y);
    
    self.collectionBackView.hidden = NO;
    self.userTableView.hidden = YES;
    self.topicView.hidden = YES;
    [self.collectionView.mj_header beginRefreshing];
}

- (IBAction)onTopic:(id)sender {
    UIButton *button = (UIButton *)sender;
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
    self.redLine.center = CGPointMake(button.center.x, self.redLine.center.y);
    
    self.collectionBackView.hidden = YES;
    self.userTableView.hidden = YES;
    self.topicView.hidden = NO;
    [self.topicTableView.mj_header beginRefreshing];
}

- (IBAction)onUser:(id)sender {
    UIButton *button = (UIButton *)sender;
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
    self.redLine.center = CGPointMake(button.center.x, self.redLine.center.y);
    
    self.collectionBackView.hidden = YES;
    self.userTableView.hidden = NO;
    self.topicView.hidden = YES;
    [self.userTableView.mj_header beginRefreshing];
}

#pragma mark - UICollectionView Delegate


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.searchVM.articlesArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NYRecommendCollectionViewCell *cell = [NYRecommendCollectionViewCell cellWithCollectionView:collectionView indePath:indexPath];
    ArticleListModel *model = [self.searchVM.articlesArray objectAtIndex:indexPath.row];
    cell.model = model;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            if (!CGSizeEqualToSize(model.imageSize, image.size)) {
                model.imageSize = image.size;
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
    }];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ArticleListModel *model = [self.searchVM.articlesArray objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
    NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
    detailVC.articleID = model.articleid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    ArticleListModel *model = [self.searchVM.articlesArray objectAtIndex:indexPath.row];
    if (!CGSizeEqualToSize(model.imageSize, CGSizeZero)) {
        return model.imageSize;
    }
    return CGSizeMake(150, 150);
}


#pragma mark UITableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.userTableView]) {
        AccountModel *model = [self.searchVM.userArray objectAtIndex:indexPath.row];
        NYSearchUserTableViewCell *cell = [NYSearchUserTableViewCell cellWithTableView:tableView];
        cell.model = model;
        return cell;
    } else {
        TopicListModel *model = [self.searchVM.topicArray objectAtIndex:indexPath.row];
        NYTopicListTableViewCell *cell = [NYTopicListTableViewCell cellWithTableView:tableView];
        cell.model = model;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.userTableView]) {
        AccountModel *model = [self.searchVM.userArray objectAtIndex:indexPath.row];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
        NYOtherUserViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYOtherUserViewController"];
        detailVC.userID = model.uid;
        [self.navigationController pushViewController:detailVC animated:YES];
    } else {
        TopicListModel *model = [self.searchVM.topicArray objectAtIndex:indexPath.row];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
        NYTopicArticlesViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
        detailVC.topicID = model.talkid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.userTableView]) {
        return self.searchVM.userArray.count;
    } else {
        return self.searchVM.topicArray.count;
    }
}


#pragma mark - saerch
- (void)onSearch:(NSString *)text{
    NSString *str = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (str.length>0) {
        self.searchVM.keys = text;
        NSMutableArray *newArray = [self.preSearchArray mutableCopy];
        
        /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
        [self.preSearchArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([text isEqualToString:obj]) {
                [newArray removeObject:obj];
                *stop = YES;
            }
        }];
        
        [newArray insertObject:text atIndex:0];
        [[NSUserDefaults standardUserDefaults] setObject:newArray forKey:@"searchList"];
        [self.preSearchArray setArray:newArray];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"searchListChange" object:newArray];
        [self.collectionView.mj_header beginRefreshing];
        [self.selectedBtn sendActionsForControlEvents:UIControlEventTouchUpInside];
    } else {
        //        NYAlertView *alert = [NYAlertView sharedAlertView];
        //        alert.title = @"请输入要查询的内容";
        //        [alert showAlert:^{
        //        }];
    }
}

- (IBAction)onTopicAll:(id)sender {
    UIButton *button = (UIButton *)sender;
    if (button.tag == 1) {
        self.searchVM.topType = @"default";
    } else if (button.tag == 2) {
        self.searchVM.topType = @"hot";
    } else {
        self.searchVM.topType = @"time";
    }
    
    self.searchVM.topicPage = 1;
    [self.topicTableView.mj_header beginRefreshing];
    
    self.selectedTopicBtn.selected = NO;
    button.selected = YES;
    self.selectedTopicBtn = button;
}


//type 搜索类型 default/hot/time 默认/最热/最新
- (IBAction)onArticleAll:(id)sender {
    UIButton *button = (UIButton *)sender;
    if (button.tag == 1) {
        self.searchVM.artType = @"default";
    } else if (button.tag == 2) {
        self.searchVM.artType = @"hot";
    } else {
        self.searchVM.artType = @"time";
    }
    self.searchVM.articlePage = 1;
    [self.collectionView.mj_header beginRefreshing];
    self.selectedArtBtn.selected = NO;
    button.selected = YES;
    self.selectedArtBtn = button;
}


-(NYSearchViewModel *)searchVM{
    if (!_searchVM) {
        _searchVM = [NYSearchViewModel new];
    }
    return _searchVM;
}

- (NSMutableArray *)preSearchArray{
    if (!_preSearchArray) {
        _preSearchArray = [NSMutableArray array];
    }
    return _preSearchArray;
}
@end
